package com.sun.filesigndemo.common.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.sun.filesigndemo.common.conf.Global;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 
 * @author winkey
 * 2017/07/10
 */
public class QiniuUpload {

	private final static Logger logger = LoggerFactory.getLogger(QiniuUpload.class);

	private final static String DOMAIN_OF_BUCKET= Global.get("app.qiniu.domainOfBucket");
	
	private final static String ACCESS_KEY = Global.get("app.qiniu.accessKey");
	
	private final static String SECRET_KEY = Global.get("app.qiniu.secretKey");
	
	private final static Long EXPIRE_IN_SECONDS = Global.getLong("app.qiniu.expireInSeconds");//3600,1小时，可以自定义链接过期时间
	 
	private final static String BUCKET = Global.get("app.qiniu.bucket");
	
	public static String getUrl(String fileName) throws UnsupportedEncodingException {
//		String encodedFileName = URLEncoder.encode(fileName, "utf-8");
		String finalUrl = String.format("%s%s", DOMAIN_OF_BUCKET, fileName);
		return finalUrl;
	}
	
	public static String privateDownload(String fileName) throws UnsupportedEncodingException {
		String encodedFileName = URLEncoder.encode(fileName, "utf-8");
		String publicUrl = String.format("%s/%s", DOMAIN_OF_BUCKET, encodedFileName);

		Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		String finalUrl = auth.privateDownloadUrl(publicUrl, EXPIRE_IN_SECONDS);
		return finalUrl;
		
	}
	
	
	public static Boolean upload(String localFilePath, String fileKey) {
		
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone2());
		//...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		String upToken = auth.uploadToken(BUCKET);
		try {
			//默认不指定key的情况下，以文件内容的hash值作为文件名
			uploadManager.put(localFilePath, fileKey, upToken);
//		    Response response = uploadManager.put(localFilePath, fileKey, upToken);
		    //解析上传成功的结果
//		    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		} catch (QiniuException ex) {
		    Response r = ex.response;
		    	logger.error(r.toString());
		    try {
		        System.err.println(r.bodyString());
		    } catch (QiniuException ex2) {
		        //ignore
		    }
		}
		return true;
	} 
	
	
	public static Boolean del(String fileKey) {
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone2());
		Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		try {
		    bucketManager.delete(BUCKET, fileKey);
		} catch (QiniuException ex) {
		    //如果遇到异常，说明删除失败
		    logger.error(ex.response.toString());
		    return false;
		}
		return true;
	} 
	
	public static void main(String[] args) {
		upload("/Users/winkey/Pictures/userImage_100px.png", "fileKey");
//		del("fileKey");
		System.out.println(DOMAIN_OF_BUCKET + "/fileKey");
	}
	
}
